package net.recursv.motific.atweaver
/**
 * Created by: recursv
 * Date: 14/08/2009
 * Time: 11:34:19 AM
 */

public class MidletTransformer {

  static boolean isMidlet(String content) {
    return content =~ /extends MIDlet/
  }

  static String addImports(String content) {

    List<String> toImport = new ArrayList<String>();
    imports.each {
      if (!content.contains(it))
        toImport.add(it)
    }

    removals.each {
      content = content.replaceAll(it, "")
    }

    return content.replaceAll(/package\s*[\w\.]+\s*;/, {it + toImport.join()})
  }

  static String[] removals = [
          "import javax.microedition.midlet.MIDlet;"
  ]

  static String[] imports = [
          "import net.recursv.motific.at.AtMidlet;",
          "import net.recursv.motific.at.impl.__Canvas;",
          "import net.recursv.motific.at.impl.__MIDlet;",
  ]

  static String implementInterface(String content) {
    return content.replaceAll(/(public\s*)?class\s*(\w[\w\d_]+)\s*extends\s*MIDlet\s*(implements \w[\w\d_]*)?\s*\{/, {a, b, c, d ->
      String ret = "";
      if (b != null)
        ret += b;
      if (c != null)
        ret += "class " + c + " "
      if (d == null)
        ret += "implements __MIDlet {" else
        ret += d + ",__MIDlet {"
      ret += _ifaceMethods.join()
      return ret;
    }).replaceAll(/protected\s+void\s+pauseApp\s*\(\)\s*\{([^\}]+)\}/, {a, b ->
      "public void pauseApp() {" + b + "__pauseAppCalled = true;}"
    }).replaceAll(/protected\s+void\s+startApp\(\)\s*throws\s+MIDletStateChangeException\s*\{([^\}]+)\}/, {a, b ->
      "public void startApp() throws MIDletStateChangeException {" + b + "__startAppCalled = true;}"
    }).replaceAll(/protected\s+void\s+destroyApp\s*\(boolean (\w[\w\d_]*)\)\s*throws\s+MIDletStateChangeException\s*\{([^\}]+)\}/, {a, b, c ->
      "public void destroyApp(boolean " + b + ") throws MIDletStateChangeException {" + c + "__destroyAppCalled = true;}"
    })
  }

  static String[] _ifaceMethods = [
          "public void notifyDestroyed() {try{destroyApp(true);} catch (MIDletStateChangeException ignored) {}}",
          "public void paint(GraphicsWrapper g) {if (__display != null) __display.doPaint(g);}",
          "public void keyPress(int keyCode) {__display.doKeyPress(keyCode);}",
          "public boolean isStartAppCalled() {return __startAppCalled;}",
          "public boolean isDestroyAppCalled() {return __destroyAppCalled;}",
          "public boolean isPauseAppCalled() {return __pauseAppCalled;}",
  ]

  static String insertFields(String content) {
    return content.replaceAll(/__MIDlet \{/, { it + _fields.join() })
  }

  static String[] _fields = [
          "private __Canvas __display;",
          "private boolean __startAppCalled;",
          "private boolean __destroyAppCalled;",
          "private boolean __pauseAppCalled;",
  ]

  static String transform(String s) {
    s = replaceMidletReferences(s)
    if (isMidlet(s)) {
      s = addImports(s)
      s = implementInterface(s)
      s = insertFields(s)
    }
    return s;
  }

  static String replaceMidletReferences(String s) {
    return s.replaceAll(/([^\w\.])MIDlet([^\.\w])/, {a, b, c -> b + "__MIDlet" + c}).replaceAll("extends __MIDlet", "extends MIDlet");
  }

}
